<template>
    <container type="top-header" class="g-width100 g-height100"  aside-style="width:320px;" main-style="padding:0px;">
        <div slot="aside" class="g-width100 g-height100">
            <MpMenu ref="mpMenu" :buttons="localButtons" :show-add-button="true" v-on:onMenuItemSelect="(menuItem)=>{selectedMenuItem = menuItem}" v-on:buttonsChange="(buttons)=>{localButtons = buttons}"></MpMenu>
            <div class="mobile-screen-operation-box g-flex g-flex-align-between g-margin-top30">
                <el-button icon="el-icon-top" class=" g-margin0" size="mini" :disabled="!(selectedMenuItem.secondIndex != null && selectedMenuItem.firstIndex != null)" @click="menuMove('up')">上移</el-button>
                <el-button icon="el-icon-bottom" class=" g-margin0" size="mini"  :disabled="!(selectedMenuItem.secondIndex != null && selectedMenuItem.firstIndex != null)" @click="menuMove('down')">下移</el-button>
                <el-button icon="el-icon-back" class=" g-margin0" size="mini"  :disabled="!(selectedMenuItem.secondIndex == null && selectedMenuItem.firstIndex != null)" @click="menuMove('left')">左移</el-button>
                <el-button icon="el-icon-right" class=" g-margin0" size="mini"  :disabled="!(selectedMenuItem.secondIndex == null && selectedMenuItem.firstIndex != null)" @click="menuMove('right')">右移</el-button>
            </div>
            <el-button icon="el-icon-refresh" type="primary" class="g-width100 g-margin-top30" :loading="pushToWxServerLoading"  @click="pushToWxServer">同步到微信服务器</el-button>
        </div>
        <div slot="main" class="g-width100 g-height100">
            <Form
                    ref="menuform"
                    :form-data="selectedMenuItem.menuItem"
                    :form-items="menuFormItems"
            ></Form>

            <slot></slot>
        </div>
    </container>
</template>

<script>
    import MpMenu from './MpMenu.vue'
    import Container from '../../../../common-util/src/components/page/Container.vue'
    import Form from '../../../../common-util/src/components/page/Form.vue'
    export default {
        components:{
            MpMenu,
            Form,
            Container
        },
        name: "MpMenuEdit",
        props:{
            appCode: {
                type: String
            },
            buttons:{
                type: Array
            },
            switchToOriginWxMpMenuJson:{
                type: Function,
                required: true
            },
        },
        computed:{

        },
        data(){
            return {
                localButtons: this.buttons,
                selectedMenuItem: {
                    firstIndex: null,
                    secondIndex: null,
                    menuItem: null
                },
                menuFormItems:[
                    {
                        field: {
                            name: 'name'
                        },
                        element:{
                            placeholder: '一级菜单最多4个汉字，二级菜单最多7个汉字',
                            required: true,
                            label: '名称'
                        }
                    },
                    {
                        field: {
                            name: 'type'
                        },
                        element:{
                            type: 'selectLocal',
                            selectLocal:{
                                groupData:[
                                    {
                                        name: '自定义菜单类型',
                                        items:[
                                            {
                                                id: 'click',
                                                name: '点击推事件'
                                            },
                                            {
                                                id: 'view',
                                                name: '跳转URL'
                                            },
                                            {
                                                id: 'scancode_push',
                                                name: '扫码推事件'
                                            },
                                            {
                                                id: 'scancode_waitmsg',
                                                name: '扫码推事件且等待'
                                            },
                                            {
                                                id: 'pic_sysphoto',
                                                name: '弹出系统拍照发图'
                                            },
                                            {
                                                id: 'pic_photo_or_album',
                                                name: '弹出拍照或者相册发图'
                                            },
                                            {
                                                id: 'pic_weixin',
                                                name: '弹出微信相册发图器'
                                            },
                                            {
                                                id: 'location_select',
                                                name: '弹出地理位置选择器'
                                            },
                                            {
                                                id: 'media_id',
                                                name: '下发消息（除文本消息）'
                                            },
                                            {
                                                id: 'view_limited',
                                                name: '跳转图文消息'
                                            },
                                            {
                                                id: 'miniprogram',
                                                name: '跳转小程序'
                                            }
                                        ]
                                    },
                                    {
                                        name: '公众号官网类型(仅供回显用，自定义菜单不支持)',
                                        items:[
                                            {
                                                id: 'text',
                                                name: '返回文本'
                                            },
                                            {
                                                id: 'img',
                                                name: '返回图片'
                                            },
                                            {
                                                id: 'photo',
                                                name: '返回照片'
                                            },
                                            {
                                                id: 'video',
                                                name: '返回视频'
                                            },
                                            {
                                                id: 'voice',
                                                name: '返回声音'
                                            }
                                        ]
                                    }
                                ]
                            },
                            label: '类型',
                            required: (form)=>{
                                // 二级菜单必填
                                return this.selectedMenuItem.secondIndex != null
                            },
                            show: (form)=>{

                                // 如果没有选择一个菜单项不显示
                                if(this.selectedMenuItem.firstIndex == null && this.selectedMenuItem.secondIndex == null){
                                    return false
                                }
                                // 一级菜单且存在二级菜单，只需要名称
                                return !(this.localButtons
                                    && this.selectedMenuItem.firstIndex != null
                                    && this.selectedMenuItem.secondIndex == null
                                    && this.localButtons[this.selectedMenuItem.firstIndex].sub_button
                                    && this.localButtons[this.selectedMenuItem.firstIndex].sub_button.list
                                    && this.localButtons[this.selectedMenuItem.firstIndex].sub_button.list.length > 0)
                            }
                        }
                    },
                    {
                        field: {
                            name: 'url'
                        },
                        element:{
                            label: 'url',
                            required: true,
                            placeholder: '网页 链接，用户点击菜单可打开链接',
                            show: (form)=>{
                                return ['view','miniprogram'].some(type=>type == form.type)
                            }
                        }
                    },

                    {
                        field: {
                            name: 'key'
                        },
                        element:{
                            label: 'key',
                            required: true,
                            show: (form)=>{
                                return ['click','scancode_push','scancode_waitmsg','pic_sysphoto','pic_photo_or_album','pic_weixin','location_select'].some(type=>type == form.type)
                            }
                        }
                    },
                    {
                        field: {
                            name: 'media_id'
                        },
                        element:{
                            label: 'media_id',
                            required: true,
                            placeholder: '调用新增永久素材接口返回的合法media_id',
                            show: (form)=>{
                                return ['media_id','view_limited'].some(type=>type == form.type)
                            }
                        }
                    },
                    {
                        field: {
                            name: 'appid'
                        },
                        element:{
                            label: 'appid',
                            required: true,
                            placeholder: '小程序的appid（仅认证公众号可配置）',
                            show: (form)=>{
                                return ['miniprogram'].some(type=>type == form.type)
                            }
                        }
                    },
                    {
                        field: {
                            name: 'pagepath'
                        },
                        element:{
                            label: 'pagepath',
                            required: true,
                            placeholder: '小程序的页面路径',
                            show: (form)=>{
                                return ['miniprogram'].some(type=>type == form.type)
                            }
                        }
                    },
                    {
                        element:{
                            type: 'button',
                            button:[
                                {
                                    action: this.saveMenuItem,
                                    label: '保存当前菜单项'
                                },
                                {
                                    action: this.deleteMenuItem,
                                    label: '删除当前菜单项'
                                }
                            ]
                        }
                    }
                ],

                pushToWxServerLoading: false
            }
        },
        mounted(){
        },
        methods:{
            getButtons(){
                return this.$refs.mpMenu.getButtons()
            },
            // 菜单移动操作
            menuMove(direction){
                let firstIndex = this.selectedMenuItem.firstIndex
                let secondIndex = this.selectedMenuItem.secondIndex
                let method = {
                    // 上移
                    up: ()=>{
                        if(secondIndex == 0){
                            return
                        }
                        let sub_button = this.localButtons[firstIndex].sub_button.list
                        let tempSubButton = sub_button.splice(secondIndex,1)[0]
                        sub_button.splice(secondIndex - 1,0,tempSubButton)

                    },
                    // 下移
                    down: ()=>{
                        if(secondIndex == this.localButtons[firstIndex].sub_button.list.length - 1){
                            return
                        }
                        let sub_button = this.localButtons[firstIndex].sub_button.list
                        let tempSubButton = sub_button.splice(secondIndex,1)[0]
                        sub_button.splice(secondIndex + 1,0,tempSubButton)

                    },
                    // 左移
                    left: ()=>{
                        if(firstIndex == 0){
                            return
                        }
                        let buttons = this.localButtons
                        let tempButton = buttons.splice(firstIndex,1)[0]
                        buttons.splice(firstIndex - 1,0,tempButton)
                    },
                    // 右移
                    right: ()=>{
                        if(firstIndex == this.localButtons.length - 1){
                            return
                        }
                        let buttons = this.localButtons
                        let tempButton = buttons.splice(firstIndex,1)[0]
                        buttons.splice(firstIndex + 1,0,tempButton)
                    },
                }
                method[direction]()
                // 调用一下这个以重新渲染
                this.localButtons.splice(firstIndex,1,this.localButtons[firstIndex])
                // 移动完清空选择，因为索引已经不正确了
                this.clearSelectedMenuItem()
            },
            // 清空已选菜单
            clearSelectedMenuItem(){
                this.$refs.menuform.resetForm()
                this.selectedMenuItem.firstIndex = null
                this.selectedMenuItem.secondIndex = null
                this.selectedMenuItem.menuItem = null
                let formData = this.$refs.menuform.getFormData()
                for (let key in formData) {
                    this.$refs.menuform.setFormItem(key,formData[key])
                }
            },
            // 推送到微信服务器
            pushToWxServer(){
                if(!this.localButtons || this.localButtons.length == 0){
                    this.$message.error('请先添加菜单或获取已经设置的菜单并进行编辑')
                    return
                }
                if(!this.appCode){
                    this.$message.error('请选择需要同步的公众号')
                    return
                }
                let originWxMpMenuJson = this.switchToOriginWxMpMenuJson(this.localButtons)
                // 如果返回空，不处理，请自行提示或其它处理
                if(!originWxMpMenuJson){
                    return;
                }
                this.pushToWxServerLoading = true

                this.axios.post(this.$baseURL.wx + '/wx/mp/menu/' + this.appCode + '/createByJson',originWxMpMenuJson)
                    .then(res=>{

                        this.$message.success('恭喜推送同步成功')
                    }).catch(error=>{
                    if(error.response){
                        if(error.response.status != 401){
                            this.$message.error(error.response.data.msg + ' 请确认所有菜单项都已保存')
                        }else{
                            this.$message.error(error.response.data.msg)
                        }
                    }else {
                        this.$message.error('网络错误或服务不可用')
                    }
                }).finally(()=>{
                    this.pushToWxServerLoading = false
                })
            },
            // 保存编辑的菜单项
            saveMenuItem(){
                let firstIndex = this.selectedMenuItem.firstIndex
                let secondIndex = this.selectedMenuItem.secondIndex
                if(firstIndex == null){
                    this.$message.error('请先选择一个菜单项')
                    return
                }
                this.$refs.menuform.validateAndSubmitForm((form)=>{

                    let button = this.localButtons[firstIndex]
                    let subButton = null
                    // 如果选中的是二级菜单
                    if(secondIndex != null){
                        subButton = button.sub_button.list[secondIndex]
                        for(let key in form){
                            subButton[key] = form[key]
                        }
                        button.sub_button.list.splice(secondIndex,1,subButton)
                    }
                    // 选中的是一级菜单
                    else{
                        for(let key in form){
                            button[key] = form[key]
                        }
                        this.localButtons.splice(firstIndex,1,button)
                    }

                    // 调用一下这个以重新渲染
                    this.localButtons.splice(firstIndex,1,this.localButtons[firstIndex])
                    this.$message.success('保存成功')
                })

            },
            // 删除菜单项
            deleteMenuItem(){

                let firstIndex = this.selectedMenuItem.firstIndex
                let secondIndex = this.selectedMenuItem.secondIndex
                if(firstIndex == null){
                    this.$message.error('请先选择一个菜单项')
                    return
                }
                let button = this.localButtons[firstIndex]
                if(secondIndex != null){
                    button.sub_button.list.splice(secondIndex,1)
                }else {
                    this.localButtons.splice(firstIndex,1)
                }



                this.clearSelectedMenuItem()
            },
        },
        watch:{
            buttons(val){
                this.localButtons = val
            }
        }
    }
</script>

<style scoped>


</style>